package com.gzhryc.shared_device.oem.h5.mng.controllers.cdb;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.MatrixToImageWriter;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.cdb.code.dao.db.BatteryCabinet;
import com.gzhryc.shared_device.cdb.code.dao.db.BatteryCabinetSlot;
import com.gzhryc.shared_device.cdb.code.dao.enums.BatteryCabinetEnum;
import com.gzhryc.shared_device.cdb.code.services.BatteryCabinetService;
import com.gzhryc.shared_device.cdb.code.services.BatteryCabinetSlotService;
import com.gzhryc.shared_device.cdb.code.services.dto.BatteryCabinetSearch;
import com.gzhryc.shared_device.common.device.dao.db.Device;
import com.gzhryc.shared_device.common.device.dao.db.DeviceType;
import com.gzhryc.shared_device.common.device.dao.db.DeviceTypeFunc;
import com.gzhryc.shared_device.common.device.services.DeviceService;
import com.gzhryc.shared_device.common.device.services.DeviceTypeFuncService;
import com.gzhryc.shared_device.common.device.services.DeviceTypeService;
import com.gzhryc.shared_device.iot.code.dao.db.IOTServerNode;
import com.gzhryc.shared_device.iot.code.services.IOTServerNodeService;
import com.gzhryc.shared_device.oem.code.device.EDeviceFunCode;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;
import com.gzhryc.shared_device.oem.h5.mng.dto.cdb.BatteryCabinetData;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class BatteryCabinetController {

    static Logger log = Logger.getLogger(BatteryCabinetController.class);

    @Route("/cdb/device/list.html")
    public String list(HttpServletRequest request) {
        request.setAttribute("stateList", BatteryCabinetEnum.State.values());
        List<String> deviceTypeIds = DeviceTypeFuncService.self().findTypeIdByCode(EDeviceFunCode.CDB.index());
        List<DeviceType> deviceTypeList = DeviceTypeService.self().findByIds(deviceTypeIds);
        if(deviceTypeList != null){
            request.setAttribute("deviceTypeList", deviceTypeList);
        }
        return "/cdb/device/list.html";
    }

    @Route(value = "/cdb/device/list.data")
    public ListResult<BatteryCabinetData> listData(HttpServletRequest request) {
        ListResult<BatteryCabinetData> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        BatteryCabinetSearch search = WebUtils.getParameter(request, BatteryCabinetSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

        result.getBody().setTotal(BatteryCabinetService.self().countJoinBySearch(search));
        List<BatteryCabinet> batteryCabinetList = BatteryCabinetService.self().findJoinBySearch(search, pageNo, pageLimit);
        if (batteryCabinetList != null && batteryCabinetList.size() > 0) {
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(new ArrayList<>());

            for (BatteryCabinet batteryCabinet : batteryCabinetList) {
                BatteryCabinetData item = ClassTools.copy(new BatteryCabinetData(), batteryCabinet);
                IOTServerNode serverNode = IOTServerNodeService.self().getById(batteryCabinet.getIotNodeId());
                if (serverNode != null) {
                    item.setIotNodeName(serverNode.getName());
                } else if (batteryCabinet.getIotNodeId() != null) {
                    item.setIotNodeName(batteryCabinet.getIotNodeId().toString());
                }
                result.getBody().getData().add(item);
            }
        }
        return result;
    }

    @Route("/cdb/device/add.html")
    public String add(HttpServletRequest request) {
        List<DeviceType> deviceTypeList = DeviceTypeService.self().findAll();
        request.setAttribute("deviceTypeList", deviceTypeList);
        List<IOTServerNode> iotNodeList = IOTServerNodeService.self().findAllUnable();
        request.setAttribute("iotNodeList", iotNodeList);
        return "/cdb/device/edit.html";
    }

    @Route(value = {"/cdb/device/add.do"})
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增共享充电宝机柜失败");
        BatteryCabinet batteryCabinet = WebUtils.getParameter(request, BatteryCabinet.class);
        try {
            DeviceType deviceType = DeviceTypeService.self().getById(batteryCabinet.getDeviceTypeId());
            if(deviceType == null){
                result.setMsg("设备类型不存在");
                return result;
            }

            DeviceTypeFunc deviceTypeFunc = DeviceTypeFuncService.self()
                    .getByKeys(batteryCabinet.getDeviceTypeId(), EDeviceFunCode.CDB.index());
            if (deviceTypeFunc == null) {
                result.setMsg("设备类型不存在此功能");
                return result;
            }
            batteryCabinet.setDeviceTypeName(deviceType.getName());
            batteryCabinet.setProtocolType(deviceTypeFunc.getProtocolType());
            if (BatteryCabinetService.self().add(batteryCabinet)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route("/cdb/device/info.html")
    public String info(HttpServletRequest request) {
        String deviceSn = WebUtils.getString(request,"deviceSn");
        BatteryCabinet batteryCabinet = BatteryCabinetService.self().getByDeviceSn(deviceSn);
        if(batteryCabinet != null) {
            WebUtils.setAttribute(request, batteryCabinet);

            Device device = DeviceService.self().getByDeviceSn(batteryCabinet.getDeviceSn());
            if (device != null) {
                request.setAttribute("device", device);
            }
        }
        return "/cdb/device/info.html";
    }

    @Route(value = "/cdb/device/slot/list.data")
    public ListResult<BatteryCabinetSlot> slotListData(HttpServletRequest request) {
        ListResult<BatteryCabinetSlot> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        String deviceSn = WebUtils.getString(request, "deviceSn");
        BatteryCabinet batteryCabinet = BatteryCabinetService.self().getByDeviceSn(deviceSn);
        if (batteryCabinet != null) {
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(new ArrayList<>());
            List<BatteryCabinetSlot> slotList = BatteryCabinetSlotService.self().findJoinByDeviceSn(deviceSn);

            for (int i = 1; i <= batteryCabinet.getSlotTotal(); i++) {
                BatteryCabinetSlot slot = null;
                if (slotList != null && slotList.size() > 0) {
                    for (BatteryCabinetSlot item : slotList) {
                        if (item.getSlotNum().equals(i)) {
                            slot = item;
                            break;
                        }
                    }
                }
                if (slot == null) {
                    slot = new BatteryCabinetSlot();
                    slot.setDeviceSn(deviceSn);
                    slot.setSlotNum(i);
                }
                result.getBody().getData().add(slot);
            }
        }
        return result;
    }

    @Route(value = { "/cdb/device/qrcode.html" })
    public String qrcode(HttpServletRequest request) {
        String deviceSn = WebUtils.getString(request, "deviceSn");
        if (StringUtils.isNotBlank(deviceSn)) {
            BatteryCabinet batteryCabinet = BatteryCabinetService.self().getByDeviceSn(deviceSn);
            if (batteryCabinet != null) {
                String httpDomain = PropertyTools.get().getString("httpDomain");
                String url = httpDomain + "/dev/cdb/" + batteryCabinet.getDeviceSn();
                request.setAttribute("url", url);
            }
        }
        return "/cdb/device/qrcode.html";
    }

    @Route(value = { "/cdb/device/qrcode.jpg" })
    public void qrcodeImg(HttpServletRequest request, HttpServletResponse response) {
        String deviceSn = WebUtils.getString(request, "deviceSn");
        if (StringUtils.isNotBlank(deviceSn)) {
            BatteryCabinet batteryCabinet = BatteryCabinetService.self().getByDeviceSn(deviceSn);
            if (batteryCabinet != null) {
                try {
                    String httpDomain = PropertyTools.get().getString("httpDomain");
                    String url = httpDomain + "/dev/cdb/" + batteryCabinet.getDeviceSn();
                    WebUtils.exportJPEG(response);
                    MatrixToImageWriter.writeToStream(url, 400, 300, "jpeg", response.getOutputStream());
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    @Route(value = { "/cdb/device/del.do" })
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除共享充电宝失败");
        String deviceSn = WebUtils.getString(request,"deviceSn");
        if(StringTools.isNotBlank(deviceSn)) {
            try {
                Device device = DeviceService.self().getByDeviceSn(deviceSn);
                if(device != null){
                    //检查设备类型对应的功能项
                    List<DeviceTypeFunc> deviceTypeFuncList = DeviceTypeFuncService.self().findByTypeId(device.getDeviceTypeId());
                    if(deviceTypeFuncList != null && deviceTypeFuncList.size() > 1) {
                        throw new LogicException("设备有"+deviceTypeFuncList.size()+"个功能项，请在设备索引列表中删除");
                    }
                    if(DeviceService.self().deleteByDeviceSn(deviceSn)){
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                }else {
                    if (BatteryCabinetService.self().deleteByDeviceSn(deviceSn)) {
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }
}
